from lxml.html import parse
from io import StringIO

def oauth(session, config, endpoint):
    # Older user agents are necessary for Google to serve the plain login form
    session.headers.update({"User-Agent": "Mozilla/4.0 (Links)"})
    out = session.get(endpoint)

    p = form_fill(out, "Email", config["Email"])
    out = session.post("https://accounts.google.com/signin/v1/lookup", data = p)

    p = form_fill(out, "Passwd", config["Password"])
    out = session.post("https://accounts.google.com/signin/challenge/sl/password", data = p)

    return out

def form_fill(out, field, value):
    form = parse(StringIO(out.text)).getroot().forms[0]
    form.fields[field] = value
    p = {}
    for (k, v) in form.form_values():
        p[k] = v
    return p
